package bold.storage.util;

import bold.storage.core.DB;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class XmlUtil {
    private static final Logger log = LoggerFactory.getLogger(DB.class);
    private static Map<String, String> sqlMap = new HashMap<>(50);
    private final static String file = "sql.xml";

    static {
        InputStream is = XmlUtil.class.getClassLoader().getResourceAsStream(file);
        if (is == null) {
            log.error(file + "does not exist");
        } else {
            Document document;
            try {
                document = new SAXReader().read(is);
                Element root = document.getRootElement(); // todo sql
                for (Iterator an = root.elementIterator(); an.hasNext(); ) {//todo an
                    Element element = (Element) an.next();
                    String id = element.attributeValue("id");
                    String text = element.getText();
                    if (id != null && !"".equals(id.trim()) && text != null && !"".equals(text.trim())) {
                        text = text.trim() + " ";
                        sqlMap.put(id, text);
                    }
                }

            } catch (DocumentException e) {
                log.error(e.getMessage());
                e.printStackTrace();
            }
        }


    }

    public static String get(String id) {
        return sqlMap.getOrDefault(id, "");
    }

    public static void main(String[] args) {
        String text = XmlUtil.get("area");
    }
}
